package org.bobo.modules.scloud.api;

import javax.servlet.http.HttpServletRequest;

import cn.hutool.core.util.RandomUtil;
import org.bobo.common.constant.enums.ExceptionEnums;
import org.bobo.common.util.RandomUtils;
import org.bobo.common.util.RedisUtil;
import org.bobo.bean.UserDO;
import org.bobo.common.constant.CommonConstant;
import org.bobo.common.util.oConvertUtils;
import org.bobo.dto.UserDTO;
import org.bobo.modules.message.websocket.WebSocket;
import org.bobo.service.IUserDOService;
import org.apache.shiro.SecurityUtils;
import org.bobo.common.api.vo.Result;

import org.bobo.common.constant.enums.MyConstant;
import org.bobo.common.exception.BusinessException;
import org.bobo.common.system.base.controller.JeecgController;
import org.bobo.common.system.query.QueryGenerator;
import org.bobo.common.aspect.annotation.AutoLog;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.extern.slf4j.Slf4j;


import org.bobo.common.system.util.JwtUtil;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;

import java.util.Date;

/**
* @Description: 用户管理
* @Author: jeecg-boot
* @Date:   2022-02-27
* @Version: V1.0
*/
@Slf4j
@Api(tags="用户端——用户管理")
@RestController
@RequestMapping("/api/user")
public class UserDOController extends JeecgController<UserDO, IUserDOService> {
   @Autowired
   private IUserDOService userDOService;
    @Autowired
    private RedisUtil redisUtil;
    @Autowired
    private WebSocket webSocket;
   /**
    * 分页列表查询
    *
    * @param userDO
    * @param pageNo
    * @param pageSize
    * @param req
    * @return
    */
   @AutoLog(value = "用户管理-分页列表查询")
   @ApiOperation(value="用户管理-分页列表查询", notes="用户管理-分页列表查询")
   @GetMapping(value = "/list")
   public Result<?> queryPageList(UserDO userDO,
                                  @RequestParam(name="pageNo", defaultValue="1") Integer pageNo,
                                  @RequestParam(name="pageSize", defaultValue="10") Integer pageSize,
                                  HttpServletRequest req) {
       QueryWrapper<UserDO> queryWrapper = QueryGenerator.initQueryWrapper(userDO, req.getParameterMap());
       Page<UserDO> page = new Page<UserDO>(pageNo, pageSize);
       IPage<UserDO> pageList = userDOService.page(page, queryWrapper);
       return Result.OK(pageList);
   }

   /**
    * 通过id查询
    *
    * @param id
    * @return
    */
   @AutoLog(value = "用户管理-通过id查询")
   @ApiOperation(value="用户管理-通过id查询", notes="用户管理-通过id查询")
   @GetMapping(value = "/queryById")
   public Result<?> queryById(@RequestParam(name="id",required=true) String id) {
       UserDO userDO = userDOService.getById(id);
       return Result.OK(userDO);
   }

    /**
     * 修改用户信息
     *
     * @param userDTO
     * @return
     */
    @AutoLog(value = "用户管理-修改用户信息")
    @ApiOperation(value="用户管理-修改用户信息", notes="用户管理-修改用户信息")
    @PostMapping(value = "/update")
    public Result<?> update(@RequestBody UserDTO userDTO) {
        userDOService.customUpdate(userDTO);
        return Result.OK("修改成功");
    }

    /**
     * 查询数据库所有的信息
     *
     * @return
     */
    @ApiOperation(value = "查询用户信息", notes = "查询用户信息")
    @GetMapping(value = "/getUserInfoById")
    public Result<?> getUserInfoByToken() {
        UserDO user=(UserDO) SecurityUtils.getSubject().getPrincipal();
        return Result.ok(user);
    }

    @AutoLog(value = "用户管理-登陆")
    @ApiOperation(value="用户管理-登陆", notes="用户管理-登陆")
    @PostMapping("/login")
    public Result<?> login(@RequestParam("username") String username,
                        @RequestParam("password") String password) {
        UserDO userBean = userDOService.findByUserNam(username);
        if(userBean==null){
            throw new BusinessException(500,"用户不存在");
        }
        if (userBean.getPassword().equals(password)) {

            String token = JwtUtil.sign(username, password, MyConstant.LOGOTYPE_USER.getValue());
            redisUtil.set(CommonConstant.PREFIX_USER_TOKEN + token, token);
            redisUtil.expire(CommonConstant.PREFIX_USER_TOKEN + token, JwtUtil.EXPIRE_TIME * 2 / 1000);
            Result<String> result=new Result<String>();
            result.setResult(token);
            result.setCode(200);
            result.setSuccess(true);
            return  result;
        } else {
            throw new BusinessException(500,"密码错误");
        }
    }

    @AutoLog(value = "用户管理-获取验证码")
    @ApiOperation(value="用户管理-获取验证码", notes="用户管理-获取验证码")
    @PostMapping("/code")
    public Result<String> code(@RequestParam("phone") String phone) {
        //在生产中这最好加一下限流策略
        String random = RandomUtils.getRandom(6);
        //验证码缓存三分钟
        redisUtil.set("sms"+phone,random,60*3);
        //假装发了短信
        return Result.OK(random);
    }

    @AutoLog(value = "用户管理-注册")
    @ApiOperation(value="用户管理-注册", notes="用户管理-注册")
    @PostMapping("/register")
    public Result<?> register(@RequestParam("username") String username,
                           @RequestParam("password") String password,@RequestParam("code") String code) {
        UserDO userBean = userDOService.findByUserNam(username);
        if(userBean!=null){
            throw new BusinessException(ExceptionEnums.USER_IS_EXIST);
        }
        //校验验证码
        String sms = (String)redisUtil.get("sms" + username);

        if(oConvertUtils.isEmpty(sms)){
            throw new BusinessException(ExceptionEnums.SMS_IS_EXIST);
        }else{
            if(!sms.equals(code)){
                throw new BusinessException(ExceptionEnums.SMS_IS_ERROR);
            }else{
                userBean=new UserDO();
                userBean.setCreateTime(new Date());
                userBean.setUserName(username);
                userBean.setDeleted(0);
                userBean.setPassword(password);
                userBean.setPhone(username);
                userBean.setRealName(String.valueOf(new Date().getTime()));
                userBean.setUpdateTime(new Date());
                userDOService.save(userBean);
            }
        }
        return Result.ok();
    }

    @Transactional
    @AutoLog(value = "用户管理-一键登陆")
    @ApiOperation(value="用户管理-一键登陆", notes="用户管理-一键登陆")
    @PostMapping("/onekeyLogin")
    public Result<?> onekeyLogin(@RequestParam("phone") String phone) {
        UserDO userBean = userDOService.findByUserNam(phone);
        if(userBean==null){
            userBean=new UserDO();
            userBean.setCreateTime(new Date());
            userBean.setUserName(phone);
            userBean.setDeleted(0);
            userBean.setPassword("123456");
            userBean.setPhone(phone);
            userBean.setRealName(String.valueOf(new Date().getTime()));
            userBean.setUpdateTime(new Date());
            if(!userDOService.save(userBean)){
                throw new BusinessException(500,"登陆失败！");
            }
        }

            String token = JwtUtil.sign(userBean.getUserName(), userBean.getPassword(), MyConstant.LOGOTYPE_USER.getValue());
            redisUtil.set(CommonConstant.PREFIX_USER_TOKEN + token, token);
            redisUtil.expire(CommonConstant.PREFIX_USER_TOKEN + token, JwtUtil.EXPIRE_TIME * 2 / 1000);
            Result<String> result=new Result<String>();
            result.setResult(token);
            result.setCode(200);
            result.setSuccess(true);
            return  result;
    }

    @AutoLog(value = "用户管理-测试sok")
    @ApiOperation(value="用户管理-测试sok", notes="用户管理-测试sok")
    @GetMapping("/sok")
    public void sok(@RequestParam("userId") String userId,
                           @RequestParam("message") String message) {
        webSocket.send2user(userId,message);
    }

}
